﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using taigu.WeChat;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using taigu.utils;

namespace taigu
{
    /*
    * 文件名:PostinfoService
    * 功能：发帖管理实现类
    * 创建时间：2021-11-15
    * 作者:gavin
    */

    public partial class PostinfoService : ApplicationService, IPostinfoService
    {
        private readonly IRepository<WeChat.PostInfo, Guid> _postInfoRepository;
        private readonly IRepository<WeChat.WeChatUsers, Guid> _weChatUsersRepository;
        private readonly IRepository<WeChat.PostComments, Guid> _postCommentsRepository;
        private readonly IRepository<WeChat.PostLike, Guid> _postLikeRepository;
        private readonly IRepository<WeChat.OrganizationStruct, Guid> _organizationStructRepository;
        public PostinfoService(IRepository<WeChat.PostInfo, Guid> postInfoRepository, IRepository<WeChat.WeChatUsers, Guid> weChatUsersRepository, IRepository<WeChat.PostComments, Guid> postCommentsRepository, IRepository<WeChat.PostLike, Guid> postLikeRepository, IRepository<WeChat.OrganizationStruct, Guid> organizationStructRepository, IConfiguration configuration)
        {
            this._configuration = configuration;
            this._postInfoRepository = postInfoRepository;
            _weChatUsersRepository = weChatUsersRepository;
            _postCommentsRepository = postCommentsRepository;
            _postLikeRepository = postLikeRepository;
            _organizationStructRepository = organizationStructRepository;

        }
        private IConfiguration _configuration;

        /// <summary>
        /// 发帖
        /// </summary>
        /// <param name="createPostInfoDto">创建DTO</param>
        /// <returns></returns>
        [AllowAnonymous]
        [Route("/community/createPost"), HttpPost]
        public async Task<ResData<string>> CreateAsync(CreatePostInfoDto createPostInfoDto)
        {
        
            try
            {
                //配置文件上传路径2021-11-27
                var fileUp = _configuration.GetSection("WxConfig:upFolder").Value;



                //当前用户如果不存在或是禁用，不可以操作 2021-11-27，后面改成aop
                var user =await _weChatUsersRepository.GetAsync(x => x.Id.ToString() == createPostInfoDto.user_id);
                if(user==null||user.status==UserStatus.disabled)
                {
                    return new ResData<string>() { Status = ResStatus.failed, Msg = "fail", Info = "" };
                }

                //获取当前登录用户的user_id
                createPostInfoDto.user_id = createPostInfoDto.user_id;
                string newbase = createPostInfoDto.image.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries)[1];

                //string imgPath = AppContext.BaseDirectory + "/up/";

                string imgPath = fileUp;//切换linux路径

                string newFileName = string.Format("{0:yyyy-MM-dd-hh-mm-ss-ffff}.jpeg", DateTime.Now);
                //base64的格式为  
                //ajax在传输过程中会将+变为空格
                byte[] imageBytes = Convert.FromBase64String(newbase.Replace(" ", "+"));
                //将base64转为图片
                using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
                {
                    //if (!Directory.Exists(imgPath))
                    //{
                    //    Directory.CreateDirectory(imgPath);
                    //}
                    System.IO.File.WriteAllBytes(imgPath + newFileName, imageBytes);
                }
                createPostInfoDto.image_url = "/up/" + newFileName;
                WeChat.PostInfo insertDto = ObjectMapper.Map<WeChat.CreatePostInfoDto, WeChat.PostInfo>(createPostInfoDto);

                WeChat.PostInfo result = await _postInfoRepository.InsertAsync(insertDto);
                return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
            }
            catch (Exception ex)
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = "fail", Info = "" };
            }
        }
        [AllowAnonymous]
        [Route("/community/updatePost"), HttpPost]
        public async Task<ResData<string>> UpdateAsync(UpdatePostInfoDto updatePostInfoDto)
        {
            try
            {
                WeChat.PostInfo model = await _postInfoRepository.GetAsync(updatePostInfoDto.Id);
                WeChat.PostInfo updateDto = ObjectMapper.Map<WeChat.UpdatePostInfoDto, WeChat.PostInfo>(updatePostInfoDto);

                WeChat.PostInfo result = await _postInfoRepository.UpdateAsync(updateDto);
                return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
            }
            catch (Exception ex)
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = "fail", Info = "" };
            }
        }

        /// <summary>
        /// 删除帖子
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [Route("/community/deletePost"), HttpPost]
        public async Task<ResData<string>> Delete(WebChat.WechatDto dto)
        {
            try
            {
                await _postInfoRepository.DeleteAsync(dto.id);
                return new ResData<string>() { Status = ResStatus.成功, Msg = "sucmsgess", Info = "" };
            }
            catch
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = "sucess", Info = "" };
            }

        }

        /// <summary>
        /// 图文详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpPost, Route("/community/getPostDetails")]
        public ResData<PostInfoSelectDto> DetailPost(WebChat.PostUserDto dto)
        {
            try
            {
                //  var test = _organizationStructRepository.Where(x => x.Id.ToString() == "22f31374-93a4-e8e7-1de9-ebd87715f859");

                var list = (from postinfo in _postInfoRepository
                            join wechatUser in _weChatUsersRepository
                            on postinfo.user_id equals wechatUser.Id
                            select new PostInfoSelectDto()
                            {
                                avatarUrl = wechatUser.avatar_url,
                                buId = wechatUser.bu_id,
                                buName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.bu_id).FirstOrDefault().name,
                                companyId = wechatUser.company_id,
                                companyName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.company_id).FirstOrDefault().name,
                                commentsCount = _postCommentsRepository.Count(x => x.post_id == postinfo.Id),
                                likesCount = _postLikeRepository.Count(x => x.post_id == postinfo.Id && x.status == PostStatus.启用),
                               content = postinfo.content,
                                createTime = postinfo.CreationTime,
                                imageUrl = postinfo.image_url,
                                isLike = _postLikeRepository.Count(x => x.post_id == postinfo.Id && x.user_id == dto.user_id && x.status == PostStatus.启用) > 0,
                                nickName = wechatUser.nick_name,
                                realName = wechatUser.real_name,
                                postId = postinfo.Id.ToString(),
                                status = postinfo.status,
                                user_id = wechatUser.Id,
                                post_order=postinfo.post_order

                            }
                            );
                // var test = list.ToList();
                var model = list.Where(x => x.postId == dto.Post_id.ToString()).FirstOrDefault();


                if (model != null)
                    return new ResData<PostInfoSelectDto>() { Status = ResStatus.成功, Msg = "sucess", Info = model };
                else
                {
                    return new ResData<PostInfoSelectDto>() { Status = ResStatus.failed, Msg = "failed", Info = { } };
                }
            }
            catch (Exception ex)
            {
                return new ResData<PostInfoSelectDto>() { Status = ResStatus.查询失败, Msg = ex.Message, Info = { } };
            }
        }
        /// <summary>
        /// 我的社区帖子
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="buId"></param>
        /// <returns></returns>
        [HttpPost, Route("/wechat/getPostList")]
        public ResData<object> GetWechatPostList(PostInfoSearchDto dto)
        {
            try
            {
                var list = (from postinfo in _postInfoRepository
                            join wechatUser in _weChatUsersRepository
                            on postinfo.user_id equals wechatUser.Id
                            select new PostInfoSelectDto()
                            {
                                avatarUrl = wechatUser.avatar_url,
                                buId = wechatUser.bu_id,
                                buName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.bu_id).FirstOrDefault().name,
                                companyId = wechatUser.company_id,
                                companyName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.company_id).FirstOrDefault().name,
                                commentsCount = _postCommentsRepository.Count(x => x.post_id == postinfo.Id),
                                likesCount = _postLikeRepository.Count(x => x.post_id == postinfo.Id && x.status == PostStatus.启用),
                                content = postinfo.content.GetPrefix(14),
                                //content =ContentHelper.GetPrefixTest( postinfo.content,14),
                                
                                createTime = postinfo.CreationTime,
                                imageUrl = postinfo.image_url,
                                isLike = _postLikeRepository.Count(x => x.post_id == postinfo.Id && x.user_id.ToString() == dto.user_id && x.status == PostStatus.启用) > 0,
                                nickName = wechatUser.nick_name,
                                realName = wechatUser.real_name,
                                postId = postinfo.Id.ToString(),
                                status = postinfo.status,
                                user_id = wechatUser.Id,
                                post_order = postinfo.post_order
                            }
                            );;

                list = list.Where(x => x.user_id.ToString() == dto.user_id);

               // list = list.OrderByDescending(x => x.post_order);

                if (dto.orderBy == "likes")
                {
                    if (dto.order == DataOrderType.asc)
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenBy(x => x.likesCount).ThenByDescending(x=>x.createTime);
                    }
                    else
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenByDescending(x => x.likesCount).ThenByDescending(x => x.createTime);
                    }
                }
                if (dto.orderBy == "date")
                {
                    if (dto.order == DataOrderType.asc)
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenBy(x => x.createTime);
                    }
                    else
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenByDescending(x => x.createTime);
                    }
                }

                int count = list.Count();

                if (dto.page < 0)
                    dto.page = 1;
                if (dto.pageSize < 0)
                    dto.pageSize = 10;
                //list = list.Take(dto.pageSize).Skip((dto.page - 1) * dto.pageSize);
                list = list.Skip((dto.page - 1) * dto.pageSize).Take(dto.pageSize);


                return new ResData<object>() { Status = ResStatus.成功, Msg = "sucess", Info = new { count = count, list = list.ToList() } };
            }
            catch (Exception ex)
            {
                return new ResData<object>() { Status = ResStatus.查询失败, Msg = ex.Message, Info = null };
            }

        }

        /// <summary>
        /// 社区帖子
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="buId"></param>
        /// <returns></returns>
        [HttpPost, Route("/community/getPostList")]
        public ResData<object> GetCommunityPostList(PostInfoSearchDto dto)
        {
            try
            {
                var list = (from postinfo in _postInfoRepository
                            join wechatUser in _weChatUsersRepository
                            on postinfo.user_id equals wechatUser.Id
                            where wechatUser.status==UserStatus.enabled && postinfo.status==PostStatus.启用//2021-11-27只查询非黑名单帐号
                            select new PostInfoSelectDto()
                            {
                                avatarUrl = wechatUser.avatar_url,
                                buId = wechatUser.bu_id,
                                buName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.bu_id).FirstOrDefault().name,
                                companyId = wechatUser.company_id,
                                companyName = _organizationStructRepository.Where(x => x.Id.ToString() == wechatUser.company_id).FirstOrDefault().name,
                                commentsCount = _postCommentsRepository.Count(x => x.post_id == postinfo.Id),
                                likesCount = _postLikeRepository.Count(x => x.post_id == postinfo.Id&&x.status==PostStatus.启用),
                                content = postinfo.content.GetPrefix(14),
                                createTime = postinfo.CreationTime,
                                imageUrl = postinfo.image_url,
                                isLike = _postLikeRepository.Count(x => x.post_id == postinfo.Id && x.user_id.ToString() == dto.user_id && x.status == PostStatus.启用) > 0,
                                nickName = wechatUser.nick_name,
                                postId = postinfo.Id.ToString(),
                                realName=wechatUser.real_name,
                                status = postinfo.status,
                                user_id = wechatUser.Id,
                                post_order = postinfo.post_order
                            }
                            );
                if (!string.IsNullOrEmpty(dto.buId))
                    list = list.Where(x => x.buId == dto.buId);
                if (!string.IsNullOrEmpty(dto.companyId))
                    list = list.Where(x => x.companyId == dto.companyId);

                if (dto.orderBy == "likes")
                {
                    if (dto.order == DataOrderType.asc)
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenBy(x => x.likesCount).ThenByDescending(x => x.createTime);
                    }
                    else
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenByDescending(x => x.likesCount).ThenByDescending(x => x.createTime);
                    }
                }
                if (dto.orderBy == "date")
                {
                    if (dto.order == DataOrderType.asc)
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenBy(x => x.createTime);
                    }
                    else
                    {
                        list = list.OrderByDescending(x => x.post_order).ThenByDescending(x => x.createTime);
                    }
                }

                int count = list.Count();

                if (dto.page < 0)
                    dto.page = 1;
                if (dto.pageSize < 0)
                    dto.pageSize = 10;
                list = list.Skip((dto.page - 1) * dto.pageSize).Take(dto.pageSize);
               

                return new ResData<object>() { Status = ResStatus.成功, Msg = "sucess", Info = new { count = count, list = list.ToList() } };
            }
            catch (Exception ex)
            {
                return new ResData<object>() { Status = ResStatus.查询失败, Msg = ex.Message, Info = null };
            }

        }
        /// <summary>
        /// 点赞，取消点赞
        /// </summary>
        /// <param name="postLikeDto"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [Route("/community/createLike"), HttpPost]
        public async Task<ResData<string>> CreateAsync(PostLikeDto postLikeDto)
        {
            try
            {
                //当前用户如果不存在或是禁用，不可以操作 2021-11-27，后面改成aop
                var user = await _weChatUsersRepository.GetAsync(x => x.Id.ToString() == postLikeDto.user_id);
                if (user == null || user.status == UserStatus.disabled)
                {
                    return new ResData<string>() { Status = ResStatus.failed, Msg = "fail", Info = "" };
                }
                PostLike postLike = await _postLikeRepository.FirstOrDefaultAsync(x => x.user_id.ToString() == postLikeDto.user_id && x.post_id.ToString() == postLikeDto.post_id);
                if (postLike == null)
                {
                    PostLike data = ObjectMapper.Map<PostLikeDto, PostLike>(postLikeDto);
                    data.status = PostStatus.启用;
                    var result = await _postLikeRepository.InsertAsync(data);
                    return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
                }
                else
                {
                    if (postLike.status == PostStatus.删除)
                        postLike.status = PostStatus.启用;
                    else
                        postLike.status = PostStatus.删除;
                    await _postLikeRepository.UpdateAsync(postLike);
                    return new ResData<string>() { Status = ResStatus.成功, Msg = "sucess", Info = "" };
                }
            }
            catch (Exception ex)
            {
                return new ResData<string>() { Status = ResStatus.failed, Msg = ex.Message, Info = "" };
            }
        }



    }
}
